package org.ascollada.core
{
	import org.ascollada.ASCollada;
	import org.ascollada.core.log.DaeLogger;
	
	public class DaeSource extends DaeElement
	{
		public var accessor		:DaeAccessor;
		
		public var type			:String;
		
		public var values		:Array;
		
		/**
		 * 
		 */ 
		public function DaeSource( document:DaeDocument, node:XML=null )
		{
			super( document, node );
		}
		
		/**
		 * Reads the node.
		 * 
		 * @param	node
		 */ 
		public override function read( node:XML ):void
		{
			if(node.name().localName != ASCollada.DAE_SOURCE_ELEMENT)
			{
				DaeLogger.error("Not a " + ASCollada.DAE_SOURCE_ELEMENT + " element!");
				throw new Error("Not a " + ASCollada.DAE_SOURCE_ELEMENT + " element!");
			}
			
			super.read( node );
			
			var children:XMLList = node.children();
			var numChildren:int = children.length();
			
			for(var i:int = 0; i < numChildren; i++)
			{
				var child:XML = children[ i ];
				
				switch( child.name().localName )
				{
					case ASCollada.DAE_TECHNIQUE_COMMON_ELEMENT:
						readTechniqueCommon(child);
						break;
					
					case ASCollada.DAE_NAME_ARRAY_ELEMENT:
					case ASCollada.DAE_IDREF_ARRAY_ELEMENT:
						this.values = readStrings( child );
						break;
						
					case ASCollada.DAE_FLOAT_ARRAY_ELEMENT:
						this.values = readFloats( child );
						break;
								
					case ASCollada.DAE_BOOL_ARRAY_ELEMENT:
						this.values = readBools( child );
						break;
						
					case ASCollada.DAE_INT_ARRAY_ELEMENT:
						this.values = readInts( child );
						break;
							
					default:
						break;
				}
			}
			
			if(this.values && this.values.length)
			{
				this.values = interweaveValues();
			}
			else
			{
				DaeLogger.warning("DaeSource : no values!");
			}
		}
		
		/**
		 * 
		 */ 
		private function interweaveValues() : Array
		{
			if(!this.accessor)
			{
				DaeLogger.warning("DaeSource: no accessor!");
				return null;
			}	
			
			var result : Array = new Array();
			var index:int = 0;
			
			for(var i:int = 0; i < this.accessor.count; i += this.accessor.stride)
			{
				var array : Array = new Array();
				
				for(var j:int = 0; j < this.accessor.stride; j++)
				{
					array.push( this.values[ index++ ] );
				}
				
				result.push( (array.length > 1 ? array : array[0]) );
			}
			
			return result;
		}
		
		/**
		 * 
		 */ 
		private function readTechniqueCommon( node:XML ):void
		{
			var children:XMLList = node.children();
			var numChildren:int = children.length();
			 
			for(var i:int = 0; i < numChildren; i++)
			{
				var child:XML = children[ i ];
				switch( child.name().localName )
				{
					case ASCollada.DAE_ACCESSOR_ELEMENT:
						this.accessor = new DaeAccessor(this.document, child);
						break;
						
					default:
						break;
				}
			}
		}
	}
}

